﻿/*******************************************************************************
* Copyright (C) sykjwh.cn
* 
* Author: liuxiang
* Create Date: 2019/02/15 
* Description: Automated building by liuxiang20041986@qq.com 
* http://www.sykjwh.cn/
*********************************************************************************/

using System;
using System.Data;
using System.IO;

namespace Sykj.Infrastructure
{
    /// <summary>
    /// 文件处理工具类
    /// </summary>
    public class FileHelper
    {
        #region 文件转换

        /// <summary>
        /// 转换为字节数组
        /// </summary>
        /// <param name="fullName">文件物理路径含文件名</param>
        /// <returns>字节数组</returns>
        public static byte[] GetBinaryFile(string fullName)
        {
            if (File.Exists(fullName))
            {
                FileStream Fsm = null;
                try
                {
                    Fsm = File.OpenRead(fullName);
                    return ConvertStreamToByteBuffer(Fsm);
                }
                catch
                {
                    return new byte[0];
                }
                finally
                {
                    Fsm.Close();
                }
            }
            else
            {
                return new byte[0];
            }
        }

        /// <summary>
        /// 流转化为字节数组
        /// </summary>
        /// <param name="theStream">流</param>
        /// <returns>字节数组</returns>
        public static byte[] ConvertStreamToByteBuffer(System.IO.Stream stream)
        {
            int bi;
            MemoryStream tempStream = new System.IO.MemoryStream();
            try
            {
                while ((bi = stream.ReadByte()) != -1)
                {
                    tempStream.WriteByte(((byte)bi));
                }
                return tempStream.ToArray();
            }
            catch
            {
                return new byte[0];
            }
            finally
            {
                tempStream.Close();
            }
        }

        #endregion

        #region 文件操作

        /// <summary>
        /// 文件流上传文件
        /// </summary>
        /// <param name="binData">字节数组</param>
        /// <param name="folder">目录</param>
        /// <param name="fileName">文件物理路径含文件名</param>
        public static bool SaveFile(byte[] binData, string folder, string fileName)
        {
            FileStream fileStream = null;
            MemoryStream m = new MemoryStream(binData);
            try
            {
                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }
                string fullName = folder + fileName;
                fileStream = new FileStream(fullName, FileMode.Create);
                m.WriteTo(fileStream);
                return true;
            }
            catch(Exception e)
            {
                return false;
            }
            finally
            {
                m.Close();
                fileStream.Close();
            }
        }

        /// <summary>
        /// 删除本地单个文件
        /// </summary>
        /// <param name="path">文件相对路径</param>
        public static bool DeleteFile(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return false;
            }
            if (File.Exists(path))
            {
                File.Delete(path);
                return true;
            }
            return false;
        }

        /// <summary>
        /// 删除指定文件夹
        /// </summary>
        /// <param name="path">文件相对路径</param>
        public static bool DeleteDirectory(string path)
        {
            if (Directory.Exists(path))
            {
                Directory.Delete(path, true);
                return true;
            }
            return false;
        }

        /// <summary>
        /// 修改指定文件夹名称
        /// </summary>
        /// <param name="olddirpath">旧相对路径</param>
        /// <param name="newdirpath">新相对路径</param>
        /// <returns>bool</returns>
        public static bool MoveDirectory(string olddirpath, string newdirpath)
        {
            if (Directory.Exists(newdirpath))
            {
                Directory.Move(olddirpath, newdirpath);
                return true;
            }
            return false;
        }

        #endregion

        #region 获取文件到集合中

        /// <summary>
        /// 读取指定位置文件列表到集合中
        /// </summary>
        /// <param name="path">指定路径</param>
        /// <returns></returns>
        public static DataTable GetFileTable(string path)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("name", typeof(string));
            dt.Columns.Add("ext", typeof(string));
            dt.Columns.Add("size", typeof(long));
            dt.Columns.Add("time", typeof(DateTime));

            DirectoryInfo dirinfo = new DirectoryInfo(path);
            FileInfo fi;
            DirectoryInfo dir;
            string FileName, FileExt;
            long FileSize = 0;
            DateTime FileModify;
            try
            {
                foreach (FileSystemInfo fsi in dirinfo.GetFileSystemInfos())
                {
                    FileName = string.Empty;
                    FileExt = string.Empty;
                    if (fsi is FileInfo)
                    {
                        fi = (FileInfo)fsi;
                        //获取文件名称
                        FileName = fi.Name;
                        //获取文件扩展名
                        FileExt = fi.Extension;
                        //获取文件大小
                        FileSize = fi.Length;
                        //获取文件最后修改时间
                        FileModify = fi.LastWriteTime;
                    }
                    else
                    {
                        dir = (DirectoryInfo)fsi;
                        //获取目录名
                        FileName = dir.Name;
                        //获取目录最后修改时间
                        FileModify = dir.LastWriteTime;
                        //设置目录文件为文件夹
                        FileExt = "文件夹";
                    }
                    DataRow dr = dt.NewRow();
                    dr["name"] = FileName;
                    dr["ext"] = FileExt;
                    dr["size"] = FileSize;
                    dr["time"] = FileModify;
                    dt.Rows.Add(dr);
                }
            }
            catch
            {

                throw;
            }
            return dt;
        }

        #endregion

        #region 文件大小转换

        /// <summary>
        ///  文件大小转为B、KB、MB、GB...
        /// </summary>
        /// <param name="size"></param>
        /// <returns></returns>
        public static string FileSizeTransf(long size)
        {
            String[] units = new String[] { "B", "KB", "MB", "GB", "TB", "PB" };
            long mod = 1024;
            int i = 0;
            while (size > mod)
            {
                size /= mod;
                i++;
            }
            return size + units[i];

        }

        /// <summary>
        /// 返回文件大小KB
        /// </summary>
        /// <param name="path">文件相对路径</param>
        /// <returns>int</returns>
        public static int GetFileSize(string path)
        {
            if (File.Exists(path))
            {
                FileInfo fileInfo = new FileInfo(path);
                return ((int)fileInfo.Length) / 1024;
            }
            return 0;
        }

        /// <summary>
        /// 返回文件扩展名，不含“.”
        /// </summary>
        /// <param name="path">文件全名称</param>
        /// <returns>string</returns>
        public static string GetFileExt(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return string.Empty;
            }
            return Path.GetExtension(path).Trim('.');
        }

        #endregion

        #region 判断指定路径是否图片文件
        /// <summary>
        /// 判断指定路径是否图片文件
        /// </summary>
        public static bool IsImageFile(string filename)
        {
            if (!File.Exists(filename))
            {
                return false;
            }
            byte[] filedata = File.ReadAllBytes(filename);
            if (filedata.Length == 0)
            {
                return false;
            }
            ushort code = BitConverter.ToUInt16(filedata, 0);
            switch (code)
            {
                case 0x4D42: //bmp
                case 0xD8FF: //jpg
                case 0x4947: //gif
                case 0x5089: //png
                    return true;
                default:
                    return false;
            }
        }

        /// <summary>
        /// 判断指定路径是否图片文件
        /// </summary>
        public static bool IsImageFile(byte[] filedata)
        {
            if (filedata.Length == 0)
            {
                return false;
            }
            ushort code = BitConverter.ToUInt16(filedata, 0);
            switch (code)
            {
                case 0x4D42: //bmp
                case 0xD8FF: //jpg
                case 0x4947: //gif
                case 0x5089: //png
                    return true;
                default:
                    return false;
            }
        }
        #endregion

    }
}
